import axios from 'axios';
import {useRouter} from 'vue-router';
import qs from 'qs';
import { message } from 'ant-design-vue';
//认证中心地址
const oauth_server = import.meta.env.VITE_APP_USER;
//客户端地址
const client_uri = import.meta.env.VITE_APP_BACK + '/back';
// Appid
const client_id = 'ffzX824G9G';//线上
// axios配置
const service = axios.create({
	timeout: 50000
})

const router=useRouter();

service.interceptors.request.use(
	(config) => {
		const zhi = getAuth();
		
		if (zhi == null) {
			fetchToken();
		} else {
			config.headers["Authorization"] = zhi.token_type + ' ' + zhi.access_token
		}
		return config;
	},
	error => {
		return Promise.reject(error)
	}
)
export interface IResponseData<T = any> {
	code: number;
	message: string;
	data: T;
}
service.interceptors.response.use(
	(respons) => {
		const res = respons.data ;

		if (res.code != 200 && res.code != 0) {
			if (res.message) {
				message.warning(res.message)

			}
			if (res.msg) {
				message.warning(res.msg)
			}
			
			return res;
		} else {
			return res;
		}
	},
	error => {

		if (error.code === 'ECONNABORTED') {
			message.error('请求超时！')
		} else if (error.response.status === 401) {
			refreshToken();
		} else if (error.response.status === 500) {
			message.error("网络错误！");
		}
		Promise.reject(error)
	}
)

export default service;


//刷新token
function refreshToken() {
	const auth = getAuth();

	const zhi = qs.stringify({
		'grant_type': 'refresh_token',
		'refresh_token': auth.refresh_token
	});
	axios.post(oauth_server + '/oauth2/token', zhi, {
		headers: {
			"Authorization": 'Basic ZmZ6WDgyNEc5RzpDMXUxRlVpcA=='
		}
	}).then((res) => {
		if (res.data.code === 200) {
			saveAuth(res.data.data);
			message.warning("用户信息已过期，将自动获取！", 1, function () {
				location.reload();
			});
		} else {
			router.replace("/login")
		}
	}).catch(() => {
		window.localStorage.removeItem('auth');
	})
}

/**
 * @description: 存入token
 */
type authType={
	access_token:string,
	token_type:string,
	refresh_token:string
}
function saveAuth(sResponse:authType) {
	localStorage.setItem("auth", JSON.stringify(sResponse));
}
/**
 * @description: 获取缓存的授权信息
 */
function getAuth():authType {

	const auth = localStorage.getItem('auth');
	return JSON.parse(auth as string);
}

/**
 * @description: 获取code
 */
function getAuthorizeUri() {
	//回调
	return window.location.href = oauth_server + '/oauth2/authorize?response_type=code&client_id=' + client_id +
		'&scope=openid&redirect_uri=' + client_uri;
}

/**
 * @description: 获取accesstoken 
 */
function fetchToken() {
	const url = window.location.toString();
	if (!url.includes('code')) {
		getAuthorizeUri();
	}
}